package com.aeky.simple.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aeky.simple.vo.AjaxResultVO;
import com.aeky.simple.vo.page.Pager;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * BaseAction
 * 
 * @author wanghui
 * 
 */
public class BaseAction extends ActionSupport implements ServletRequestAware, ServletResponseAware {

    private static final long serialVersionUID = 5391306463008756688L;

    private static final Logger logger = LoggerFactory.getLogger(BaseAction.class);

    public HttpServletRequest request;

    public HttpServletResponse response;

    protected ActionContext context = ActionContext.getContext();

    public HttpSession session;

    protected String ajaxResult;

    protected static final String AJAX_RESULT = "ajaxResult";

    public void setServletResponse(HttpServletResponse response) {
        this.response = response;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
    }

    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
        this.session = request.getSession(true);
    }

    /**
     * 判断ajax过来的请求,是否需要登录或登录超时，冲突
     * 
     * @return
     * @throws IOException
     */
    public boolean needLoginAjax() throws IOException {
        boolean validateAjaxLogin = true;
        if (validateAjaxLogin) {
            String msg = "timeout";
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(msg);
            response.getWriter().flush();
            response.getWriter().close();
            return true;
        }
        return false;
    }

    public String getLoginUserName() {
        return "admin";
    }

    public void print(HttpServletResponse res, String content) {
        PrintWriter writer = null;
        try {
            res.setCharacterEncoding("UTF-8");
            writer = res.getWriter();
            writer.write(content);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            logger.error("IOException!can't get writer");
            res.setStatus(500);
        }
    }

    /**
     * 创建Ajax请求json格式数据返回结果
     * 
     * @param result
     * @param msg
     * @return
     */
    protected String buildJSONResponse(String result, String msg) {
        AjaxResultVO ar = new AjaxResultVO();
        ar.setResult(result);
        ar.setMsg(msg);
        return this.getJsonFromObject(ar);
    }

    /**
     * 对象转json
     * 
     * @param obj
     * @return
     */
    protected String getJsonFromObject(Object obj) {
        Gson gson = new GsonBuilder().create();
        return gson.toJson(obj);
    }

    /**
     * 把服务端返回数据转成页面端map格式数据
     * 
     * @param fromPager
     * @return
     * @throws Exception
     */
    protected <T> Pager<Map<String, Object>> changeToMapPager(Pager<T> fromPager) throws Exception {
        Pager<Map<String, Object>> returnPager = new Pager<Map<String, Object>>();
        returnPager.setPageNum(fromPager.getPageNum());
        returnPager.setPageSize(fromPager.getPageSize());
        returnPager.setTotal(fromPager.getTotal());
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        for (T t : fromPager.getRows()) {
            result.add(converterObjectToMap(t));
        }
        returnPager.setRows(result);
        return returnPager;
    }

    /**
     * 把对象转车Map格式
     * 
     * @param t
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public <T> Map<String, Object> converterObjectToMap(T t) throws Exception {
        Map<String, Object> m = BeanUtils.describe(t);
        this.addOtherMapValue(t, m);
        return m;
    }

    /**
     * 子类可重写此方法添加额外的map属性
     * 
     * @param t
     * @param map
     */
    public <T> void addOtherMapValue(T t, Map<String, Object> map) {

    }

    public String getAjaxResult() {
        return ajaxResult;
    }

}
